package com.jswlw.controller;

import com.jswlw.common.utils.DateUtils;
import com.jswlw.common.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * 文件上传处理类
 */
@RestController
@RequestMapping("/file")
public class FileUploadController extends BaseController {

    @Value("${file.uploadDir}")
    private String uploadDir;

    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    public ModelAndView upload() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("file/upload");
        return modelAndView;
    }

    /**
     * 文件异步上传方法
     *
     * @param file
     * @return
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ModelMap upload(MultipartFile file, HttpServletRequest request) {
        try {
            String path = "/upload/" + DateUtils.nowDate() + "/";
            String realPath = uploadDir + DateUtils.nowDate() + "/";
            File pathFile = new File(realPath);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }

            String upFileName = file.getOriginalFilename();
            String fileType = upFileName.substring(upFileName.lastIndexOf("."), upFileName.length());

            String fileName = UUIDUtils.uuid32() + fileType;

            realPath = realPath + "/" + fileName;
            File newFile = new File(realPath);
            //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
            file.transferTo(newFile);
            return this.successResult(path + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return this.failResult("上传文件失败");
        }
    }
}
